package com.bonc.modules.business.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.bonc.common.utils.ConfigConstant;
import com.bonc.common.utils.HttpUtils;
import com.bonc.common.utils.JsonUtils;
import com.bonc.common.utils.MapUtils;
import com.bonc.common.utils.Result;
import com.bonc.modules.business.entity.TbWorkOrderInfoEntity;
import com.bonc.modules.business.entity.TbWorkOrderReplyEntity;
import com.bonc.modules.business.service.TbWorkOederDistributionService;
import com.bonc.modules.business.service.TbWorkOrderArchiveService;
import com.bonc.modules.business.service.TbWorkOrderCancelService;
import com.bonc.modules.business.service.TbWorkOrderInfoService;
import com.bonc.modules.business.service.TbWorkOrderReplyService;
import com.bonc.modules.business.service.TbWorkOrderReproceeService;
import com.bonc.modules.business.service.TbWorkOrderUrgeService;

@RestController
@RequestMapping("/workorderForProvince")
public class WorkOrderForProvinceController {

	@Value("${oa.WorkOrderUrl}")
	private String workOrderUrl;

	@Value("${oa.QueryWorkOrderUrl}")
	private String queryWorkOrderUrl;

    @Autowired
    private TbWorkOrderInfoService tbWorkOrderInfoService;
    @Autowired
    private TbWorkOederDistributionService tbWorkOederDistributionService;
    @Autowired
    private TbWorkOrderCancelService tbWorkOrderCancelService;
    @Autowired
    private TbWorkOrderReproceeService tbWorkOrderReproceeService;
    @Autowired
    private TbWorkOrderUrgeService tbWorkOrderUrgeService;
    @Autowired
    private TbWorkOrderArchiveService tbWorkOrderArchiveService;

    @Autowired
    private TbWorkOrderReplyService tbWorkOrderReplyService;

	/**
	 * 	工单（派发、撤单、再处理、归档、催办）
	 *
	 * @return
	 */
    @RequestMapping("/workOrder")
	public Result workOrder() {
    	List<Map<String,Object>> archiveList = tbWorkOrderArchiveService.queryArchiveList();
    	List<Map<String,Object>> urgeList = tbWorkOrderUrgeService.queryUrgeList();
    	List<Map<String,Object>> cancelList = tbWorkOrderCancelService.queryCancelList();
    	List<Map<String,Object>> reproceeList = tbWorkOrderReproceeService.queryReproceeList();
    	List<Map<String,Object>> distributionList = tbWorkOederDistributionService.queryDistributionList();

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		list.addAll(distributionList);
		list.addAll(cancelList);
		list.addAll(reproceeList);
		list.addAll(urgeList);
		list.addAll(archiveList);

		for (Map<String, Object> map : list) {
			if(map.get("extEarlyWarningLevel")==null) {
				map.put("extEarlyWarningLevel", "");
			}
			if(map.get("dataFileNameList")==null) {
				map.put("dataFileNameList", "");
			}
			if(map.get("extEarlyWarningThreshold")==null) {
				map.put("extEarlyWarningThreshold", "");
			}
			if(map.get("filingOpinion")==null) {
				map.put("filingOpinion", "");
			}
			if(map.get("withdrawTime")==null) {
				map.put("withdrawTime", "");
			}
			if(map.get("withdrawReason")==null) {
				map.put("withdrawReason", "");
			}
			if(map.get("creator")==null) {
				map.put("creator", "");
			}
			if(map.get("creatorTel")==null) {
				map.put("creatorTel", "");
			}
			if(map.get("reprocessingOpinion")==null) {
				map.put("reprocessingOpinion", "");
			}
			if(map.get("urgeTime")==null) {
				map.put("urgeTime", "");
			}
			if(map.get("urgeReason")==null) {
				map.put("urgeReason", "");
			}
			if(map.get("identyDetail")==null) {
				map.put("identyDetail", "");
			}
			if(map.get("processTime")==null) {
				Calendar calendar= Calendar.getInstance();
	            SimpleDateFormat dateFormat= new SimpleDateFormat("YYYYMMDDHHMMSS");
	            String time = dateFormat.format(calendar.getTime());
				map.put("processTime", time);
			}
			
			String identifier = map.get("identifier")==null ? "": (String) map.get("identifier");
			String orderType = map.get("orderType")==null ? "": (String) map.get("orderType");
			String identyType = map.get("identyType")==null ? "": (String) map.get("identyType");//派单必传
			String identySubtype = map.get("identySubtype")==null ? "": (String) map.get("identySubtype");//派单必传
			String title = map.get("title")==null ? "": (String) map.get("title");//派单必传
			String content = map.get("content")==null ? "": (String) map.get("content");//派单必传
			String originUnit = map.get("originUnit")==null ? "": (String) map.get("originUnit");//派单必传
			String receiverUnit = map.get("receiverUnit")==null ? "": (String) map.get("receiverUnit");//派单必传
			
			String extEarlyWarningLevel = map.get("extEarlyWarningLevel")==null ? "": (String) map.get("extEarlyWarningLevel");//0002必传、0003必传
			String dataFileNameList = map.get("dataFileNameList")==null ? "": (String) map.get("dataFileNameList");//005必传、0201必传
			String extEarlyWarningThreshold = map.get("extEarlyWarningThreshold")==null ? "": (String) map.get("extEarlyWarningThreshold");//0006必传
			String filingOpinion = map.get("filingOpinion")==null ? "": (String) map.get("filingOpinion");//归档必传
			String withdrawTime = map.get("withdrawTime")==null ? "": (String) map.get("withdrawTime");//撤单必传
			String withdrawReason = map.get("withdrawReason")==null ? "": (String) map.get("withdrawReason");//撤单必传
			String creator = map.get("creator")==null ? "": (String) map.get("creator");//再处理必传
			String creatorTel = map.get("creatorTel")==null ? "": (String) map.get("creatorTel");//再处理必传
			String reprocessingOpinion = map.get("reprocessingOpinion")==null ? "": (String) map.get("reprocessingOpinion");//再处理必传
			String urgeTime = map.get("urgeTime")==null ? "": (String) map.get("urgeTime");//催办必传
			String urgeReason = map.get("urgeReason")==null ? "": (String) map.get("urgeReason");//催办必传
			String responsible = map.get("responsible")==null ? "": (String) map.get("responsible");

			if(StringUtils.isBlank(identifier) || StringUtils.isBlank(orderType) || StringUtils.isBlank(responsible) ){
				return Result.error("缺少公共必传参数！");
	        }

			if(ConfigConstant.IDENTY_TYPE_00.equals(orderType)) {
				if(StringUtils.isBlank(identyType) ||
						StringUtils.isBlank(identySubtype) ||
						StringUtils.isBlank(title) ||
						StringUtils.isBlank(content) ||
						StringUtils.isBlank(originUnit) ||
						StringUtils.isBlank(receiverUnit)) {
					return Result.error(identifier+"派单缺少必传参数！");
				}
				if((ConfigConstant.IDENTY_SUB_TYPE_0002.equals(identySubtype) || ConfigConstant.IDENTY_SUB_TYPE_0003.equals(identySubtype)) && StringUtils.isBlank(extEarlyWarningLevel)) {
					return Result.error(identifier+"(0002产品、003产品)缺少必传参数！");
				}
				if(ConfigConstant.IDENTY_SUB_TYPE_0005.equals(identySubtype) && StringUtils.isBlank(dataFileNameList)) {
					return Result.error(identifier+"(0005产品)缺少必传参数！");
				}
				if(ConfigConstant.IDENTY_SUB_TYPE_0006.equals(identySubtype) && StringUtils.isBlank(extEarlyWarningThreshold)) {
					return Result.error(identifier+"(0006产品)缺少必传参数！");
				}
			}

			if(ConfigConstant.IDENTY_SUB_TYPE_0201.equals(identySubtype) && StringUtils.isBlank(dataFileNameList)) {
				return Result.error(identifier+"(0201产品)缺少必传参数！");
			}

			if(ConfigConstant.ORDER_TYPE_01.equals(orderType) && (StringUtils.isBlank(withdrawTime) || StringUtils.isBlank(withdrawReason))) {
				return Result.error(identifier+"撤单缺少必传参数！");
			}

			if(ConfigConstant.ORDER_TYPE_02.equals(orderType) && (StringUtils.isBlank(creator) || StringUtils.isBlank(creatorTel) || StringUtils.isBlank(reprocessingOpinion))) {
				return Result.error(identifier+"再处理缺少必传参数！");
			}

			if(ConfigConstant.ORDER_TYPE_03.equals(orderType) && (StringUtils.isBlank(urgeTime) || StringUtils.isBlank(urgeReason))) {
				return Result.error(identifier+"催办缺少必传参数！");
			}

			if(ConfigConstant.ORDER_TYPE_04.equals(orderType) && StringUtils.isBlank(filingOpinion)) {
				return Result.error(identifier+"归档缺少必传参数！");
			}
			map  = MapUtils.nullToEmpty(map);
			String json = JsonUtils.map2String(map);
			String result = HttpUtils.doPost(workOrderUrl, json);
			System.out.println("=========================================");
			System.out.println(json);
			System.out.println(result);
			//修改省内处理状态
			Map<String, Object> resultMap = MapUtils.json2Map(result);
			if("1".equals((String)resultMap.get("state"))) {
				tbWorkOrderInfoService.updateHandingStatus(identifier);
			}
		}
		return Result.ok();
	}

	/**
	 * 	工单（回复）
	 *
	 * @param params
	 * @return
	 */
	@PostMapping("/ReturnWorkOrder")
	public Result returnWorkOrder(@RequestBody String param) {
		JSONObject json = JSONObject.parseObject(param);
		System.out.println("==>"+param);
		String identifier = (String) json.get("identifier");
		String handlingOpinion = (String) json.get("handlingOpinion");
		String handler = (String) json.get("handler");
		String handlerInfor = (String) json.get("handlerInfor");
		String handingTime = (String) json.get("handingTime");
		if (StringUtils.isBlank(identifier)
				|| StringUtils.isBlank(handlingOpinion)
				|| StringUtils.isBlank(handler)
				|| StringUtils.isBlank(handlerInfor)
				|| StringUtils.isBlank(handingTime)) {
			return Result.error("缺少必传参数！");
		}
		//获取工单
        TbWorkOrderInfoEntity tbWorkOrderInfo = tbWorkOrderInfoService.getById(identifier);
        if(tbWorkOrderInfo == null){
        	return Result.error("此工单不存在，请检查！");
        }else if(ConfigConstant.WORK_ORDER_STATUS_01.equals(tbWorkOrderInfo.getState()) || ConfigConstant.WORK_ORDER_STATUS_06.equals(tbWorkOrderInfo.getState())){
            // 插入工单回复表
        	TbWorkOrderReplyEntity reply = new TbWorkOrderReplyEntity();
        	reply.setIdentifier(identifier);
        	reply.setHandlingOpinion(handlingOpinion);
        	reply.setHandler(handler);
        	reply.setHandlerInfor(handlerInfor);
        	reply.setHandingTime(handingTime);
        	reply.setHandlerRank(json.get("handlerRank")==null ? "":(String) json.get("handlerRank"));
        	reply.setHandingDepartment(json.get("handingDepartment")==null ? "":(String) json.get("handingDepartment"));
        	reply.setAttachList(json.get("attachList")==null ? "":(String) json.get("attachList"));
        	reply.setImprovementPoints(json.get("improvementPoints")==null ? "":(String) json.get("improvementPoints"));
        	reply.setImprovementMode(json.get("improvementMode")==null ? "":(String) json.get("improvementMode"));
        	reply.setPackageName(json.get("packageName")==null ? "":(String) json.get("packageName"));
        	reply.setPackageCode(json.get("packageCode")==null ? "":(String) json.get("packageCode"));
        	reply.setPromotionName(json.get("promotionName")==null ? "":(String) json.get("promotionName"));
			reply.setSelfEvaluation(json.get("selfEvaluation")==null ? "":(String) json.get("selfEvaluation"));
        	reply.setPromotionCode(json.get("promotionCode")==null ? "":(String) json.get("promotionCode"));
        	tbWorkOrderReplyService.save(reply);
            // 修改工单状态
        	HashMap<String, Object> map = new HashMap<String, Object>();
        	map.put("identifier", identifier);
        	map.put("handlingOpinion", handlingOpinion);
        	map.put("handingDepartment", reply.getHandingDepartment());
        	map.put("handler", handler);
        	map.put("handlerInfor", handlerInfor);
        	map.put("state", ConfigConstant.WORK_ORDER_STATUS_04);
        	Calendar calendar= Calendar.getInstance();
            SimpleDateFormat dateFormat= new SimpleDateFormat("YYYYMMDDHHMMSS");
            String time = dateFormat.format(calendar.getTime());
        	map.put("handingTime", time);
        	tbWorkOrderInfoService.updateStatus(map);
        }else {
        	return Result.error("该工单状态错误！");
        }
        Result r = new Result();
        r.put("code", 1);
        r.put("msg", "success");
		return r;
	}

	/**
	 * 	工单查询
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping("/queryCSS")
	public Result queryWorkOrder(@RequestBody String param) {
		JSONObject json = JSONObject.parseObject(param);
		String identifier = (String) json.get("identifier");
		String queryType = (String) json.get("queryType");
		if(StringUtils.isBlank(identifier) || StringUtils.isBlank(queryType)) {
			return Result.error("缺少必传参数！");
		}
		String result = HttpUtils.doPost(queryWorkOrderUrl, param);
		System.out.println("=========>");
		System.out.println(param);
		System.out.println(result);
		Map<String, Object> map = MapUtils.json2Map(result);
		return Result.ok(map);
	}
}
